package com.pwc.conversionTool.relation.xml;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;



/**
 * dependency --dom4j
 * @author yuanhuang
 *
 */
public class XMLFactory {
	
	private Document document;
	
	/**
	 * 
	 * @param document
	 */
	public XMLFactory(Document document)
	{
		this.document=document;
	}
	
	public XMLFactory(String xmlString) throws DocumentException
	{
		SAXReader reader = new SAXReader();
		 document = reader.read(new StringReader(xmlString));
	}
	
	/**
	 * 
	 * @return
	 */
	public XMLNode getRootNode()
	{
		Element root = document.getRootElement();
		
		XMLNode node=new XMLNode(root.getName(),root.getPath(),"");
		XMLNode resultNode=nodeWalk(document.getRootElement(),node);
		
		return resultNode;
	}
	
	
	/**
	 * 
	 * @param element
	 */
	private XMLNode nodeWalk(Element element,XMLNode node) {
		
		List<XMLNode> childrenList=new ArrayList<XMLNode>();
		List<XMLAttribute> attributes=new  ArrayList<XMLAttribute>();
		
		for (int i = 0, size = element.nodeCount(); i < size; i++) {
			Node domNode = element.node(i);
			if (domNode instanceof Element) {
				XMLNode thisNode=new XMLNode(domNode.getName(),domNode.getPath(),domNode.getText().trim());
				XMLNode childNode=	 nodeWalk((Element) domNode,thisNode);				
				attributes= attributesWalk(  (List<Node>)((Element)domNode).attributes());
				childrenList.add(childNode);
				
				System.out.println(domNode.getName());
				
			} else {
					// doing sth
			}
		}
		node.setAttributes(attributes);
		node.setChildren(childrenList);
		return node;
	}
	
	/**
	 * loop for attribute
	 * @param attrList
	 * @return
	 */
	private List<XMLAttribute> attributesWalk(List<Node> attrList)
	{
		List<XMLAttribute> result=new  ArrayList<XMLAttribute>();
		
		for(Node e: attrList)
		{
			result.add(new XMLAttribute(e.getName(),e.getPath(),e.getText().trim()));
		}
		
		return result;
	}
	

}
